//
//  TestPostsController.swift
//  maopu
//
//  Created by 黄海波 on 2017/4/26.
//  Copyright © 2017年 maopu. All rights reserved.
//

import UIKit

class TestPostsController: UIViewController , UITextViewDelegate{
    @IBOutlet var textView:UITextView!
    @IBOutlet var textViewHeight:NSLayoutConstraint!
    @IBOutlet var bottomView:UIView!
    
    @IBOutlet var scrollerView:UIScrollView!
    
    fileprivate var keyBoardHeight:CGFloat = 0
    
    init(){
        super.init(nibName: "TestPostsController", bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        self.textView.delegate = self
        self.textView.isScrollEnabled = false
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        NotificationCenter.default.addObserver(self, selector:#selector(self.keyBoardWillShow(_:)), name:NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector:#selector(self.keyBoardWillHide(_:)), name:NSNotification.Name.UIKeyboardWillHide, object: nil)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        NotificationCenter.default.removeObserver(self)
    }
    
    func keyBoardWillShow(_ note:Notification){
        KeyBoardUtils.shared.keyBoardWillShow(note, showView: self.bottomView) { (keyBoardHeight) in
            self.keyBoardHeight = keyBoardHeight
        }
    }
    
    func keyBoardWillHide(_ note:Notification){
        KeyBoardUtils.shared.keyBoardWillHide(note, hideView: self.bottomView) {
            
        }
    }

    func textViewDidChange(_ textView: UITextView) {
        let height = StringSizeEngine.calculateStringHeight(textView.text, width: AppWidth - 40 , font: textView.font!)
        if height > 128{
            UIView.animate(withDuration: 0.5) {
                self.textViewHeight.constant = height + 10
                self.view.layoutIfNeeded()
            }
            if self.textView.frame.maxY > self.keyBoardHeight{
                self.scrollerView.setContentOffset(CGPoint.init(x: 0, y: -(self.textView.frame.maxY - self.keyBoardHeight)), animated: false)
            }
            
        }else{
            UIView.animate(withDuration: 0.5) {
                self.textViewHeight.constant = 128
                self.view.layoutIfNeeded()
            }
        }
        
    }

}
